package com.zhentao.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.zhentao.service.UserService;
import com.zhentao.service.OrderService;
import com.zhentao.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ProductPayUtil {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    
    //appid
    private final String APP_ID = "9021000149677539";
    //应用私钥 - 用于签名
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCNwLL8vcJK/b16AYQV+rNjv2QNpIW6XjSD7nDNIakM1i9OU2atpu4ZP/rcf/kkT+Lc0OSEKR/kH6zANmlRzgbXcyeV0pAfHkI66nhSwmHxHKSCxouyJJzqPLDfumQEscQ4tZviJFF1DrSA6K1qmLadiGHAilGS2tptTWrc6xdjId2+pIBrjqA4NDqwVEPEihs6NyI9VsM2pZQwlTIq/ERT1Li8iNlZLip7PDkJoEkgZpLhYMH33QUwsrQ4oe0U/zOKswtdFBZ5mfUyl3ko9obiwI53PTz8agdKx11LsyzcghNPL8jPr/xmKJqTm/o+EaI4tl/YEwqObhe1vNZLvt41AgMBAAECggEAEZmQX5ML8ZWpleFkTfpPlZ3oxUzdEbOqn4rWVJHOVHqvavEt+XeVbmskMYZuH5UPnM0O4l3cyM0p/L+EuhRzgwKYMqDvJf3yyS/deqEJ2g7tWhNeuuKS3P5mE5En4/FSZJwf26cYugj2Xl8FUQve+JY7VNWXpT0pC5MmJoHF6JfXOUbpCr9sMQv721QzgMhJhhS5WwY+UFetucEs7eAUQZ541/MPo88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PAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhyXO0YA9B4Vz7EagPzm/dGEw2VRlhfi7TC9+OFDAah/H6R0oA2+cXYO33/t8mmBDoka3uz1EXbrGCRit2mXaCSiuJqssA8hGaVOINqSImHWg2JBeZdLGk1zAW27xep+vl9t5rdqT9pOdQmYhaUPk0JTZXHWd30SOl5+0BjfQWh/5UfgzUYZSG1dKbmaHZ8vD4YOaRTt5VMyr5f4Cg8uUdTJ0UumCxCtlZAQDczWHoFvX7CZLj0qR/jv5CR/FI3h1CZHUgXD85Yd8Vb2ZryjgZmFV2u8mbAuEPCBBaxaVpIaWUMVXocQjjDs1PDlP5PNibC+6CWNDiiO2cKEgCm8KVQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://y5ace563.natappfree.cc/api/productpay/toSuccess";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://y5ace563.natappfree.cc/api/productpay/toSuccess";
    private AlipayClient alipayClient = null;
    
    //支付宝官方提供的接口
    public String sendRequestToAlipay(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body = "产品订单购买";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("支付宝支付页面返回结果："+result );
        return result;
    }

    //    通过订单编号查询
    public String query(String id){
        // 初始化AlipayClient
        if (alipayClient == null) {
            alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        }
        
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String body=null;
        try {
            response = alipayClient.execute(request);
            body = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
    
    // 生成支付链接（用于二维码）
    public String generatePaymentUrl(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        try {
            // 使用alipay.trade.precreate接口生成二维码
            return generateQRCodeUrl(outTradeNo, totalAmount, subject);
            
        } catch (AlipayApiException e) {
            System.err.println("生成支付链接异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    // 使用alipay.trade.precreate接口生成二维码URL
    private String generateQRCodeUrl(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        try {
            // 获得初始化的AlipayClient
            alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

            // 创建预下单请求
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            request.setNotifyUrl(NOTIFY_URL);

            //商品描述（可空）
            String body = "产品订单购买";
            
            // 构建biz_content JSON字符串
            String bizContent = "{\"out_trade_no\":\"" + outTradeNo + "\","
                    + "\"total_amount\":\"" + totalAmount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\"}";
            
            System.out.println("设置的biz_content: " + bizContent);
            request.setBizContent(bizContent);

            // 执行请求
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            
            if (response.isSuccess()) {
                String qrCode = response.getQrCode();
                System.out.println("生成的二维码内容: " + qrCode);
                return qrCode;
            } else {
                System.err.println("预下单失败: " + response.getMsg());
                throw new AlipayApiException("预下单失败: " + response.getMsg());
            }
            
        } catch (AlipayApiException e) {
            System.err.println("生成二维码异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    // Getter方法用于配置检查
    public String getAppPrivateKey() {
        return APP_PRIVATE_KEY;
    }
    
    public String getAlipayPublicKey() {
        return ALIPAY_PUBLIC_KEY;
    }
}
